package com.erp.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.erp.dto.Apply;
import com.erp.dto.Examine;
import com.erp.dto.TimeOff;
import com.erp.dto.User;
import com.erp.mapping.ApplyStatus;

@SuppressWarnings("serial")
@Controller(value = "timeOffAction")
@Scope(value = "prototype")
public class TimeOffAction extends ModelDrivenBaseAction<TimeOff> {

	/**
	 * 填写请假单页面
	 */
	public String addPage() throws Exception {
		return "addPage";
	}

	/**
	 * 提交请假单
	 */
	public void add() throws Exception {

		User applicant = (User) session.get("user");

		// 使用请假流程定义的key来启动流程实例
		String procInstId = workflowService.startProcessInstanceByKey("timeoff");

		// 提交申请
		model.setApplicant(applicant);
		model.setApplyTime(new Date());
		model.setStatus(ApplyStatus.EXAMING);
		model.setProcInstId(procInstId);
		// 保存申请表信息
		Integer applyId = timeOffService.add(model);
		// 将表单的ID设置为流程变量
		workflowService.setVariable(procInstId, "applyId", applyId);

		// 执行请假申请任务
		workflowService.completeTaskByProcInstId(procInstId, applicant.getName());

		// 提示下一个执行者的姓名
		String auditorName = workflowService.getAssignee(procInstId);
		User auditor = userService.getUserByName(auditorName);
		// 设置下一个审核者的审批意见为待查看
		model.setId(applyId);
		examineService.addNext(model, auditor);
		
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("msg", "true");
		jsonMap.put("auditor", auditorName);
		super.writeJson(jsonMap);
	}

	public String show() {
		// 申请表概览
		Apply apply = (Apply) request.get("apply");
		// 申请表（请假表）详情
		TimeOff timeOff = timeOffService.getById(apply.getId());
		super.pushIntoValueStack(timeOff);
		// 审批流程记录
		List<Examine> examineList = examineService.getExamineListByApply(apply);
		request.put("examineList", examineList);
		return "show";
	}
}
